#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/stat.h>
#include <stdint.h>

#define MAX_PACKET_SIZE 1024
#define MAX_DATA_SIZE 1000
#define SYNC_HEAD 0x5AA5
#define PACKET_END 0x96

// 帧类型和报文类型
#define FRAME_TYPE 0x05
#define PACKET_TYPE_REQUEST 0xCC  // 请求上传
#define PACKET_TYPE_DATA 0xCD     // 图像数据
#define PACKET_TYPE_END 0xCE      // 上传结束

// CRC16校验表
static const uint16_t crc16_table[256] = {
    0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
    0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
    0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
    0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
    0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
    0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
    0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
    0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
    0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
    0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
    0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
    0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
    0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
    0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
    0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
    0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
    0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
    0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
    0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
    0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
    0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
    0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
    0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
    0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
    0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
    0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
    0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
    0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
    0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
    0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
    0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
    0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};

// CRC32校验表
static const uint32_t crc32_table[256] = {
    0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,
    0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
    0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2,
    0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
    0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
    0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
    0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,
    0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
    0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423,
    0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
    0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106,
    0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
    0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,
    0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
    0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
    0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
    0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7,
    0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
    0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA,
    0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
    0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
    0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
    0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84,
    0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
    0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
    0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
    0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E,
    0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
    0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55,
    0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
    0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28,
    0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
    0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F,
    0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
    0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
    0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
    0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69,
    0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
    0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC,
    0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
    0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693,
    0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
    0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};

// 配置结构体
typedef struct {
    char device_id[18];     // 17位设备ID + '\0'
    uint8_t channel_no;     // 通道号
    uint8_t preset_no;      // 预置位号
    uint8_t frame_seq;      // 帧序列号（递增）
} device_config_t;

// CRC16校验
uint16_t calculate_crc16(const uint8_t* data, size_t length) {
    uint16_t crc = 0x0000;
    for (size_t i = 0; i < length; i++) {
        crc = (crc >> 8) ^ crc16_table[(crc ^ data[i]) & 0xFF];
    }
    return crc;
}

// CRC32校验
uint32_t calculate_crc32(const uint8_t* data, size_t length) {
    uint32_t crc = 0xFFFFFFFF;
    for (size_t i = 0; i < length; i++) {
        crc = (crc >> 8) ^ crc32_table[(crc ^ data[i]) & 0xFF];
    }
    return ~crc;
}

// 获取当前时间戳（Unix时间戳）
uint32_t get_timestamp() {
    return (uint32_t)time(NULL);
}

// 构建请求上传报文（05 CC）
int build_request_packet(uint8_t* packet, device_config_t* config, uint32_t timestamp) {
    int pos = 0;
    
    // 报文头
    packet[pos++] = 0x5A;
    packet[pos++] = 0xA5;
    
    // 报文长度（暂时填0，后面计算）
    packet[pos++] = 0x00;
    packet[pos++] = 0x00;
    
    // 设备ID（17字节）
    memcpy(&packet[pos], config->device_id, 17);
    pos += 17;
    
    // 帧类型
    packet[pos++] = FRAME_TYPE;
    
    // 报文类型
    packet[pos++] = PACKET_TYPE_REQUEST;
    
    // 帧序列号
    packet[pos++] = config->frame_seq++;
    
    // 通道号
    packet[pos++] = config->channel_no;
    
    // 预置位号
    packet[pos++] = config->preset_no;
    
    // 包数高位和低位（请求时为0）
    packet[pos++] = 0x00;
    packet[pos++] = 0x00;
    
    // 备用字段（8字节）
    packet[pos++] = 0x00; // 文件类型：0=图像
    packet[pos++] = 0x00; // 图片存在标识（主站填写）
    packet[pos++] = 0x00; // 预留
    packet[pos++] = 0x00; // 预留
    // 时间戳（4字节，Little Endian）
    packet[pos++] = (timestamp >> 0) & 0xFF;
    packet[pos++] = (timestamp >> 8) & 0xFF;
    packet[pos++] = (timestamp >> 16) & 0xFF;
    packet[pos++] = (timestamp >> 24) & 0xFF;
    
    // 计算并填入报文长度
    uint16_t length = pos + 3; // 包含CRC16(2字节) + END(1字节)
    packet[2] = (length >> 8) & 0xFF;
    packet[3] = length & 0xFF;
    
    // 计算CRC16（不包含CRC16字段本身和END字段）
    uint16_t crc16 = calculate_crc16(packet, pos);
    packet[pos++] = (crc16 >> 8) & 0xFF;
    packet[pos++] = crc16 & 0xFF;
    
    // 报文尾
    packet[pos++] = PACKET_END;
    
    return pos;
}

// 构建图像数据报文（05 CD）
int build_data_packet(uint8_t* packet, device_config_t* config, 
                     uint16_t total_packets, uint16_t packet_no,
                     uint32_t image_id, uint32_t offset,
                     const uint8_t* image_data, int data_len) {
    int pos = 0;
    
    // 报文头
    packet[pos++] = 0x5A;
    packet[pos++] = 0xA5;
    
    // 报文长度（暂时填0，后面计算）
    packet[pos++] = 0x00;
    packet[pos++] = 0x00;
    
    // 设备ID（17字节）
    memcpy(&packet[pos], config->device_id, 17);
    pos += 17;
    
    // 帧类型
    packet[pos++] = FRAME_TYPE;
    
    // 报文类型
    packet[pos++] = PACKET_TYPE_DATA;
    
    // 帧序列号
    packet[pos++] = config->frame_seq++;
    
    // 通道号
    packet[pos++] = config->channel_no;
    
    // 预置位号
    packet[pos++] = config->preset_no;
    
    // 总包数（2字节，大端序）
    packet[pos++] = (total_packets >> 8) & 0xFF;
    packet[pos++] = total_packets & 0xFF;
    
    // 子包包号（2字节，大端序）
    packet[pos++] = (packet_no >> 8) & 0xFF;
    packet[pos++] = packet_no & 0xFF;
    
    // 数据区：图像报头（8字节）+ 图像数据
    // 图像ID（4字节）
    packet[pos++] = (image_id >> 0) & 0xFF;
    packet[pos++] = (image_id >> 8) & 0xFF;
    packet[pos++] = (image_id >> 16) & 0xFF;
    packet[pos++] = (image_id >> 24) & 0xFF;
    
    // 偏移量（4字节）
    packet[pos++] = (offset >> 0) & 0xFF;
    packet[pos++] = (offset >> 8) & 0xFF;
    packet[pos++] = (offset >> 16) & 0xFF;
    packet[pos++] = (offset >> 24) & 0xFF;
    
    // 图像数据
    memcpy(&packet[pos], image_data, data_len);
    pos += data_len;
    
    // 计算并填入报文长度
    uint16_t length = pos + 3; // 包含CRC16(2字节) + END(1字节)
    packet[2] = (length >> 8) & 0xFF;
    packet[3] = length & 0xFF;
    
    // 计算CRC16
    uint16_t crc16 = calculate_crc16(packet, pos);
    packet[pos++] = (crc16 >> 8) & 0xFF;
    packet[pos++] = crc16 & 0xFF;
    
    // 报文尾
    packet[pos++] = PACKET_END;
    
    return pos;
}

// 构建上传结束报文（05 CE）
int build_end_packet(uint8_t* packet, device_config_t* config, uint32_t timestamp, uint32_t image_crc32) {
    int pos = 0;
    
    // 报文头
    packet[pos++] = 0x5A;
    packet[pos++] = 0xA5;
    
    // 报文长度（暂时填0，后面计算）
    packet[pos++] = 0x00;
    packet[pos++] = 0x00;
    
    // 设备ID（17字节）
    memcpy(&packet[pos], config->device_id, 17);
    pos += 17;
    
    // 帧类型
    packet[pos++] = FRAME_TYPE;
    
    // 报文类型
    packet[pos++] = PACKET_TYPE_END;
    
    // 帧序列号
    packet[pos] = config->frame_seq++;
    
    // 通道号
    packet[pos++] = config->channel_no;
    
    // 预置位号
    packet[pos++] = config->preset_no;
    
    // 时间戳（4字节）
    packet[pos++] = (timestamp >> 0) & 0xFF;
    packet[pos++] = (timestamp >> 8) & 0xFF;
    packet[pos++] = (timestamp >> 16) & 0xFF;
    packet[pos++] = (timestamp >> 24) & 0xFF;
    
    // 备用字段（8字节）
    packet[pos++] = 0x00; // 文件类型：0=图像
    packet[pos++] = 0x00; // 预留
    packet[pos++] = 0x00; // 预留
    packet[pos++] = 0x00; // 预留
    //CRC16校验
    uint16_t image_crc16 = (uint16_t)(image_crc32 & 0xFFFF);
    packet[pos++] = (image_crc16 >> 0) & 0xFF;
    packet[pos++] = (image_crc16 >> 8) & 0xFF;
    packet[pos++] = 0x00;
    packet[pos++] = 0x00;
    
    // 计算并填入报文长度
    uint16_t length = pos + 3; // 包含CRC16(2字节) + END(1字节)
    packet[2] = (length >> 8) & 0xFF;
    packet[3] = length & 0xFF;
    
    // 计算CRC16
    uint16_t crc16 = calculate_crc16(packet, pos);
    packet[pos++] = (crc16 >> 8) & 0xFF;
    packet[pos++] = crc16 & 0xFF;
    
    // 报文尾
    packet[pos++] = PACKET_END;
    
    return pos;
}

// 发送报文并等待回复
int send_and_receive(int sockfd, const uint8_t* packet, int packet_len, uint8_t* response, int max_response_len) {
    // 发送报文
    if (send(sockfd, packet, packet_len, 0) < 0) {
        perror("发送失败");
        return -1;
    }
    
    printf("已发送 %d 字节: ", packet_len);
    for (int i = 0; i < packet_len; i++) {
        printf("%02X ", packet[i]);
    }
    printf("\n");
    
    // 设置接收超时
    struct timeval timeout;
    timeout.tv_sec = 5;
    timeout.tv_usec = 0;
    setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
    
    // 接收回复
    int recv_len = recv(sockfd, response, max_response_len, 0);
    if (recv_len <= 0) {
        printf("接收回复失败或超时\n");
        return -1;
    }
    
    printf("收到回复 %d 字节: ", recv_len);
    for (int i = 0; i < recv_len; i++) {
        printf("%02X ", response[i]);
    }
    printf("\n");
    
    return recv_len;
}

// 上传图片
int upload_image(int sockfd, device_config_t* config, const char* image_path) {
    FILE* fp = fopen(image_path, "rb");
    if (!fp) {
        perror("打开图片文件失败");
        return -1;
    }
    
    // 获取文件大小
    fseek(fp, 0, SEEK_END);
    long file_size = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    
    printf("图片文件大小: %ld 字节\n", file_size);
    
    // 读取整个文件到内存
    uint8_t* image_data = malloc(file_size);
    if (!image_data) {
        printf("内存分配失败\n");
        fclose(fp);
        return -1;
    }
    
    if (fread(image_data, 1, file_size, fp) != file_size) {
        printf("读取文件失败\n");
        free(image_data);
        fclose(fp);
        return -1;
    }
    fclose(fp);
    
    // 计算图片CRC16校验（使用CRC32算法但只取低16位）
    uint32_t image_crc32 = calculate_crc32(image_data, file_size);
    uint16_t image_crc16 = (uint16_t)(image_crc32 & 0xFFFF);
    uint32_t timestamp = get_timestamp();
    uint32_t image_id = timestamp; // 使用时间戳作为图片ID
    
    printf("图片CRC16: 0x%04X\n", image_crc16);
    printf("时间戳: %u\n", timestamp);
    printf("图片ID: %u\n", image_id);
    
    // 计算需要的包数
    int max_data_per_packet = MAX_DATA_SIZE - 8; // 减去8字节图像报头
    uint16_t total_packets = (file_size + max_data_per_packet - 1) / max_data_per_packet;
    
    printf("总包数: %d\n", total_packets);
    
    uint8_t packet[MAX_PACKET_SIZE];
    uint8_t response[MAX_PACKET_SIZE];
    int retry_count;
    
    // 第一步：发送请求上传报文（05 CC）
    printf("\n=== 第一步：发送请求上传报文 ===\n");
    for (retry_count = 0; retry_count < 5; retry_count++) {
        int packet_len = build_request_packet(packet, config, timestamp);
        int response_len = send_and_receive(sockfd, packet, packet_len, response, MAX_PACKET_SIZE);
        
        if (response_len > 0) {
            // 检查回复是否为相同的报文类型
            if (response_len >= 24 && response[21] == PACKET_TYPE_REQUEST) {
                // 检查备用字段第二个字节（图片存在标识）
                if (response[32] == 0x01) {
                    printf("主站回复：图片已存在，无需上传\n");
                    free(image_data);
                    return 0;
                } else {
                    printf("主站回复：可以开始上传图片\n");
                    break;
                }
            }
        }
        
        if (retry_count < 4) {
            printf("等待3秒后重试...\n");
            sleep(3);
        }
    }
    
    if (retry_count >= 5) {
        printf("请求上传失败，已重试5次\n");
        free(image_data);
        return -1;
    }
    
    // 第二步：发送图像数据报文（05 CD）
    printf("\n=== 第二步：发送图像数据 ===\n");
    uint32_t offset = 0;
    
    for (uint16_t packet_no = 0; packet_no < total_packets; packet_no++) {
        int data_len = (offset + max_data_per_packet <= file_size) ? 
                       max_data_per_packet : (file_size - offset);
        
        int packet_len = build_data_packet(packet, config, total_packets, packet_no,
                                         image_id, offset, &image_data[offset], data_len);
        
        printf("发送数据包 %d/%d (偏移: %u, 长度: %d)\n", 
               packet_no + 1, total_packets, offset, data_len);
        
        if (send(sockfd, packet, packet_len, 0) < 0) {
            printf("发送数据包失败\n");
            free(image_data);
            return -1;
        }
        
        offset += data_len;
        
        // 简单的进度显示
        if ((packet_no + 1) % 10 == 0 || packet_no == total_packets - 1) {
            printf("进度: %d/%d (%.1f%%)\n", 
                   packet_no + 1, total_packets, 
                   (float)(packet_no + 1) * 100 / total_packets);
        }
    }
    
    printf("图像数据发送完成\n");
    
    // 等待2秒
    sleep(2);
    
    // 第三步：发送上传结束报文（05 CE）
    printf("\n=== 第三步：发送上传结束报文 ===\n");
    for (retry_count = 0; retry_count < 5; retry_count++) {
        int packet_len = build_end_packet(packet, config, timestamp, image_crc32);
        int response_len = send_and_receive(sockfd, packet, packet_len, response, MAX_PACKET_SIZE);
        
        if (response_len > 0) {
            // 检查回复是否为相同的报文类型
            if (response_len >= 24 && response[21] == PACKET_TYPE_END) {
                printf("主站确认：图片上传完成\n");
                break;
            }
        }
        
        if (retry_count < 4) {
            printf("等待3秒后重试...\n");
            sleep(3);
        }
    }
    
    if (retry_count >= 5) {
        printf("上传结束确认失败，但图片数据已发送完成\n");
    }
    
    free(image_data);
    return 0;
}

int main(int argc, char* argv[]) {
    if (argc < 6) {
        printf("用法: %s <IP> <端口> <设备ID> <图片路径> [通道号] [预置位号]\n", argv[0]);
        printf("示例: %s 222.175.245.230 40010 FDZHYCS20040605031 image.jpg 1 255\n", argv[0]);
        return 1;
    }
    
    // 解析参数
    const char* server_ip = argv[1];
    int server_port = atoi(argv[2]);
    const char* device_id = argv[3];
    const char* image_path = argv[4];
    
    device_config_t config;
    strncpy(config.device_id, device_id, 17);
    config.device_id[17] = '\0';
    config.channel_no = (argc >= 6) ? atoi(argv[5]) : 1;
    config.preset_no = (argc >= 7) ? atoi(argv[6]) : 255;
    config.frame_seq = 1;
    
    printf("配置信息:\n");
    printf("  服务器: %s:%d\n", server_ip, server_port);
    printf("  设备ID: %s\n", config.device_id);
    printf("  图片路径: %s\n", image_path);
    printf("  通道号: %d\n", config.channel_no);
    printf("  预置位号: %d\n", config.preset_no);
    
    // 检查图片文件是否存在
    struct stat file_stat;
    if (stat(image_path, &file_stat) != 0) {
        printf("图片文件不存在: %s\n", image_path);
        return 1;
    }
    
    // 创建socket连接
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("创建socket失败");
        return 1;
    }
    
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip);
    
    if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        perror("连接服务器失败");
        close(sockfd);
        return 1;
    }
    
    printf("已连接到主站\n\n");
    
    // 上传图片
    int result = upload_image(sockfd, &config, image_path);
    
    close(sockfd);
    
    if (result == 0) {
        printf("\n图片上传成功！\n");
    } else {
        printf("\n图片上传失败！\n");
    }
    
    return result;
}